package com.example.elm.StoreAndGoods

import com.example.elm.Public.GoodsInfo
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.elm.Public.MyApplication
import com.example.elm.Public.StoreInfo
import com.example.elm.R
import com.example.elm.databinding.StoreBinding
import okhttp3.OkHttpClient
import okhttp3.Request
import org.xmlpull.v1.XmlPullParser
import org.xmlpull.v1.XmlPullParserFactory
import java.io.StringReader
import kotlin.concurrent.thread

class StoreActivity : ComponentActivity() {
    private lateinit var binding:StoreBinding
    private val server_ip = MyApplication.serverIp
    private val GoodsList = ArrayList<GoodsInfo>()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = StoreBinding.inflate(layoutInflater)
        setContentView(binding.root)

        // 接收从 HomeMainFragment 传递过来的数据,
        // 并将店家名填充上去
        var StoreData = intent.getStringExtra("store_data").toString()
        binding.storeName.text = StoreData
        binding.storeResult.text = StoreData+"的搜索结果"
        if (StoreData == "重庆小面") {
            binding.storeImage.setImageResource(R.drawable.cqxm)
        } else if (StoreData == "明哥烤肉拌饭"){
            binding.storeImage.setImageResource(R.drawable.mgkrbf)
        } else if (StoreData == "三个先生·韩式炸鸡·芝士球"){
            binding.storeImage.setImageResource(R.drawable.sgxs)
        } else if (StoreData == "钱小匠·爆汁牛肉饭"){
            binding.storeImage.setImageResource(R.drawable.qxj)
        } else if (StoreData == "淮南牛肉汤"){
            binding.storeImage.setImageResource(R.drawable.hnnrt)
        } else if (StoreData == "干饭人拌饭-木桶饭"){
            binding.storeImage.setImageResource(R.drawable.mtf)
        }

        //初始化
        ReadGoodsByXml(StoreData)
        val layoutManager =LinearLayoutManager(this)
        binding.menuRecycler.layoutManager = layoutManager
        val adapter = GoodsAdapter(GoodsList)
        binding.menuRecycler.adapter = adapter
    }



    private class ViewHolder(view:View):RecyclerView.ViewHolder(view){
        val a1 = view.findViewById<TextView>(R.id.a1)
        val a2 = view.findViewById<TextView>(R.id.a2)
        val a3 = view.findViewById<TextView>(R.id.a3)
        val a0 = view.findViewById<Button>(R.id.a0)
        val a4 = view.findViewById<ImageView>(R.id.a4)
        val a5 = view.findViewById<TextView>(R.id.a5)
    }
    private class GoodsAdapter(val GoodsList: ArrayList<GoodsInfo>):RecyclerView.Adapter<ViewHolder>(){
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
            val view = LayoutInflater.from(parent.context)
                .inflate(R.layout.goods_item,parent,false)
            return ViewHolder(view)
        }
        override fun getItemCount(): Int {
            return GoodsList.size
        }
        override fun onBindViewHolder(holder: ViewHolder, position: Int) {
            val goodsInfo = GoodsList[position]
            holder.a1.text = goodsInfo.name
            holder.a2.text = goodsInfo.comment
            holder.a3.text = goodsInfo.info
            holder.a5.text = "￥"+"${goodsInfo.price}"
            holder.a0.setOnClickListener{
                val GoodData = goodsInfo
                val intent = Intent(holder.itemView.context,GoodsActivity::class.java)
                intent.putExtra("good_data", GoodData)
                holder.itemView.context.startActivity(intent)
            }

            val imageResid =holder.itemView.context.resources.getIdentifier(
                goodsInfo.image,"drawable",holder.itemView.context.packageName
            )
            if (imageResid != 0) {
                holder.a4.setImageResource(imageResid)
            } else {
                holder.a4.setImageResource(R.drawable.aa1)
            }
        }
    }

    // 通过xml读取
    fun ReadGoodsByXml(StoreName : String){
        val goods_all = "http://$server_ip:8080/StoreAndGoods/get_all_Goods_xml.jsp"
        thread {
            try{
                val client = OkHttpClient()
                val request: Request = Request.Builder()
                    .url(goods_all)
                    .build()
                val response = client.newCall(request).execute()
                val responseData = response.body?.string()
                // 确保在主线程更新 UI
                    if (!responseData.isNullOrEmpty()) {
                        parseXml(responseData.trim(), StoreName) // 解析返回的数据
                    } else {
                        Log.d("StoreGetGoods", "没有数据")
                    }
            }
            catch (e: Exception){
                e.printStackTrace()
                Log.d("StoreGetGoods", "加载失败，请检查网络")
            }
        }
    }
    // 解析xml
    fun parseXml(xmlStr: String, StoreName : String): String{
        try {
            val factory = XmlPullParserFactory.newInstance()
            val xmlPullPaser = factory.newPullParser()
            // 设置xml解析器的输入
            xmlPullPaser.setInput(StringReader(xmlStr))
            GoodsList.clear()
            var eventType = xmlPullPaser.eventType//  事件类型
            var name = ""
            var comment = ""
            var info = ""
            var image = ""
            var store = ""
            var priceStr = ""
            while(eventType != XmlPullParser.END_DOCUMENT){
                val nodeName = xmlPullPaser.name
                // builder.append("${nodeName}--")
                when(eventType) {
                    // 标签开始
                    XmlPullParser.START_TAG -> {
                        when (nodeName) {
                            "name" -> name = xmlPullPaser.nextText()
                            "comment" -> comment = xmlPullPaser.nextText()
                            "info" -> info = xmlPullPaser.nextText()
                            "image" -> image = xmlPullPaser.nextText()
                            "store" -> store = xmlPullPaser.nextText()
                            "price" -> priceStr = xmlPullPaser.nextText()
                        }
                    }
                    // 标签结束
                    XmlPullParser.END_TAG -> {
                        if ("Goods" == nodeName) {
                            if (store == StoreName) {
                                GoodsList.add(
                                    GoodsInfo(
                                        name,
                                        comment,
                                        info,
                                        image,
                                        store,
                                        priceStr.toDoubleOrNull()?:0.0
                                    )
                                )
                            }
                        }
                    }
                }
                eventType = xmlPullPaser.next() //  读取下一个，进行遍历
            }
            binding.menuRecycler.adapter?.notifyDataSetChanged()
        }
        catch (e: Exception){
            e.printStackTrace()
        }
        return ""
    }
}